package com.fj.netty.rpc.client.handler;

import com.fj.netty.rpc.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.DefaultPromise;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    public static final Map<Integer, DefaultPromise<Object>> PROMISE_MAP = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage message) throws Exception {
        //设置promise结果，并从map中移除
        DefaultPromise<Object> promise = PROMISE_MAP.remove(message.getSequenceId());
        if (promise!=null){
            if (message.getExceptionValue()!=null) {
                promise.setFailure(message.getExceptionValue());
            }else{
                promise.setSuccess(message.getReturnValue());
            }
        }
    }
}
